package com.iweb.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Configuration
@EnableCaching
public class RedisConfig {

    // 设定缓存失效时间
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        // 创建缓存空间
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add("articles");
        // TO ADD ...
        // 对每个空间进行配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        RedisCacheConfiguration articlesConfig = RedisCacheConfiguration.defaultCacheConfig()
                // 设置缓存时间
                .entryTtl(Duration.ofSeconds(20))
                // 禁止缓存空数据
                .disableCachingNullValues();
        configMap.put("articles", articlesConfig);

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(articlesConfig)
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
    }
}
